<template>
  <div>
    <!-- 显示选择框,默认展开,关闭父子关联 -->
    <el-tree
      ref="refTree"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      :data="list"
      node-key="id"
      :props="{label:'name',children:'children'}"
    />
    <el-row type="flex" justify="end" height="60">
      <el-button type="primary" @click="hSave">确定</el-button>
      <el-button type="info" @click="hCancel">取消</el-button>
    </el-row>
  </div>
</template>
<script>
import { getRolesDetail, assignPerm } from '@/api/settings'
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils/tranListToTreeData'
export default {
  props: {
    roleid: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []// 权限数组
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
  // 获取权限列表函数
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.list = tranListToTreeData(res.data)
        const info = await getRolesDetail(this.roleid)
        console.log('info', info)
        this.permIds = info.data.permIds
        // console.log(this.list)
        // 回填数据
        this.$refs.refTree.setCheckedKeys(info.data.permIds)
        // 保存数据
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 点击确定修改权限
    async hSave() {
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        // console.log('当前选中的节点数组是', permIds)
        const res = await assignPerm({
          id: this.roleid,
          permIds
        })
        console.log('保存角色的权限点的结果是', res)
        // 提示
        this.$message.success('保存角色的权限成功')
        // 关闭弹层
        this.hCancel()
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    hCancel() {
      this.$emit('close')
      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    }
  }
}
</script>
